﻿using Castle.Core.Logging;
using Castle.DynamicProxy;
using System;
using System.Linq;
using System.Reflection;
using System.Transactions;
using Abp.Dependency;

namespace Abp.Application.Transactions
{
    /// <summary>
    /// 事物拦截器
    /// </summary>
    public class TransactionInterceptor : IInterceptor
    {
        private ILogger Logger { get; set; }

        public TransactionInterceptor()
        {
            Logger = ObjectContainer.Resolve<ILogger>();
        }
        public void Intercept(IInvocation invocation)
        {
            MethodInfo methodInfo = invocation.MethodInvocationTarget;

          
            if (methodInfo == null)
            {
                methodInfo = invocation.Method;
            }
            if (methodInfo.IsDefined(typeof(TransactionAttribute), true))
            {
                TransactionAttribute transactionConfiguration = methodInfo.GetCustomAttribute<TransactionAttribute>(true);
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionConfiguration.ScopeTimeout))
                {
                    try
                    {
                        invocation.Proceed();
                        transactionScope.Complete();
                    }
                    catch (Exception ex)
                    {
                        string message = "事务发生异常,原因:" + ex.Message;
                        Logger.Error(message, ex);
                        throw new Exception(message, ex);
                    }
                    finally
                    {
                        transactionScope.Dispose();
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }

        }
    }
}
